package com.wxisme.ssm.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wxisme.ssm.po.Album;
import com.wxisme.ssm.po.Photo;
import com.wxisme.ssm.po.UserInfo;
import com.wxisme.ssm.service.AlbumService;
import com.wxisme.ssm.service.PhotoService;
import com.wxisme.ssm.service.UserInfoService;
import com.wxisme.ssm.util.FilesToZip;
import com.wxisme.ssm.util.MultiZip;

/**
 *photo
 *@author wxisme
 *@time 2015-9-18 下午12:29:23
 */
@Controller
public class PhotoController {
	
	
	@Autowired
	private PhotoService photoService;
	
	@Autowired
	private AlbumService albumService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	
	/**
	 * 上传照片
	 * @param request
	 * @param session
	 * @param photoFile
	 * @param description
	 * @param selectedAlbum
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadPhoto.action")
	public ModelAndView uploadPhoto(HttpServletRequest request, HttpSession session, 
			MultipartFile photoFile, String description, String selectedAlbum) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		
		
		//上传图片
		if(photoFile != null) {
			String albumPath = request.getServletContext().getRealPath("/")
					+ "imgdata/" + session.getAttribute("username") + "file/" + selectedAlbum +"/";
			
			String photoPathName = UUID.randomUUID().toString();
			
			String original = photoFile.getOriginalFilename();
			
			String photoName = photoPathName + original.substring(original.lastIndexOf("."));
			
			String photoPath = albumPath + photoName;

			//将照片信息写入数据库
			Photo photo = new Photo();
			photo.setAlbumPathName(selectedAlbum);
			photo.setDescription(description);
			photo.setPathName(photoName);
			photo.setUploadTime((new Date()).getTime());
			photoService.insertPhoto(photo);
			
			//将照片写入对应的文件路径
			photoFile.transferTo(new File(photoPath));
			
			//更新user的photoNumber,album的photoNumber,session中的photo记录
			Map<Album, List<Photo>> albumList = (Map<Album, List<Photo>>) session.getAttribute("userLoadingMap");
			int photoNumber = 0;
			for(Album album : albumList.keySet()) {
				if(album.getPathName().equals(selectedAlbum)) {
					albumList.get(album).add(photo);
					photoNumber = albumList.get(album).size();
					album.setPhotoNumber(photoNumber);
					albumService.updatePhotoNumber(album);
					break;
				}
			}
			
			
			String username = (String) session.getAttribute("username");
			UserInfo userInfo = userInfoService.selectUserInfoByUsername(username);
			userInfo.setPhotoNumber(userInfo.getPhotoNumber()+1);
			userInfoService.updatePhotoNumber(userInfo);
			
			
			modelAndView.addObject("calbum", selectedAlbum);
			modelAndView.setViewName("photoDisplay");
			
			
		}
		
		
		
		return modelAndView;
		
	}
	
	
	/**
	 * 查看前一张
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/prePhoto.action")
	public ModelAndView prePhoto(HttpSession session, HttpServletRequest request) {
		
		ModelAndView modelAndView = new ModelAndView();
		
		List<Photo> photo_list = (List<Photo>) session.getAttribute("photo_list");
		
		int this_num = (Integer) session.getAttribute("this_num");
		int pre = this_num;
		
		Photo photo = null;
		
		String alPath = (String) session.getAttribute("alPath");
		
		StringBuilder imgPath = new StringBuilder(alPath);
		if(this_num > 1) {
			imgPath.append(photo_list.get(this_num - 2).getPathName());
			photo = photo_list.get(this_num - 2);
			pre --;
		}
		
		else {
			imgPath.append(photo_list.get(this_num - 1).getPathName());
			photo = photo_list.get(this_num - 1);
		}
		
		
		Date date = new Date(photo.getUploadTime());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String time = sdf.format(date);
		
		
		modelAndView.addObject("pre", pre);
		modelAndView.addObject("imgPath", imgPath.toString());
		modelAndView.addObject("totol", photo_list.size());
		modelAndView.addObject("description", photo.getDescription());
		modelAndView.addObject("time", time);
		
		modelAndView.setViewName("preOrnextPhoto");
		
		return modelAndView;
	}
	
	
	/**
	 * 查看后一张
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/nextPhoto.action")
	public ModelAndView nextPhoto(HttpSession session, HttpServletRequest request) {
		
		ModelAndView modelAndView = new ModelAndView();
		
		List<Photo> photo_list = (List<Photo>) session.getAttribute("photo_list");
		
		int this_num = (Integer) session.getAttribute("this_num");
		int next = this_num;
		
		Photo photo = null;
		
		String alPath = (String) session.getAttribute("alPath");
		
		StringBuilder imgPath = new StringBuilder(alPath);
		if(this_num < photo_list.size()) {
			imgPath.append(photo_list.get(this_num).getPathName());
			photo = photo_list.get(this_num);
			next ++;
		}
		
		else {
			imgPath.append(photo_list.get(this_num - 1).getPathName());
			photo = photo_list.get(this_num - 1);
		}
		
		
		Date date = new Date(photo.getUploadTime());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String time = sdf.format(date);
		
		modelAndView.addObject("next", next);
		modelAndView.addObject("imgPath", imgPath.toString());
		modelAndView.addObject("totol", photo_list.size());
		modelAndView.addObject("description", photo.getDescription());
		modelAndView.addObject("time", time);
		
		modelAndView.setViewName("preOrnextPhoto");
		
		return modelAndView;
	}
	
	
	/**
	 * 在共享空间查看前一张
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/preFriendPhoto.action")
	public ModelAndView preFriendPhoto(HttpSession session, HttpServletRequest request) {
		
		ModelAndView modelAndView = new ModelAndView();
		
		List<Photo> photo_list = (List<Photo>) session.getAttribute("friend_photo_list");
		
		int this_num = (Integer) session.getAttribute("friend_this_num");
		int pre = this_num;
		
		Photo photo = null;
		
		String alPath = (String) session.getAttribute("friend_alPath");
		
		StringBuilder imgPath = new StringBuilder(alPath);
		if(this_num > 1) {
			imgPath.append(photo_list.get(this_num - 2).getPathName());
			photo = photo_list.get(this_num - 2);
			pre --;
		}
		
		else {
			imgPath.append(photo_list.get(this_num - 1).getPathName());
			photo = photo_list.get(this_num - 1);
		}
		
		
		Date date = new Date(photo.getUploadTime());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String time = sdf.format(date);
		
		
		modelAndView.addObject("pre", pre);
		modelAndView.addObject("imgPath", imgPath.toString());
		modelAndView.addObject("totol", photo_list.size());
		modelAndView.addObject("description", photo.getDescription());
		modelAndView.addObject("time", time);
		
		modelAndView.setViewName("preOrnextFriendPhoto");
		
		return modelAndView;
	}
	
	
	/**
	 * 在共享空间查看后一张
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/nextFriendPhoto.action")
	public ModelAndView nextFriendPhoto(HttpSession session, HttpServletRequest request) {
		
		ModelAndView modelAndView = new ModelAndView();
		
		List<Photo> photo_list = (List<Photo>) session.getAttribute("friend_photo_list");
		
		int this_num = (Integer) session.getAttribute("friend_this_num");
		int next = this_num;
		
		Photo photo = null;
		
		String alPath = (String) session.getAttribute("friend_alPath");
		
		StringBuilder imgPath = new StringBuilder(alPath);
		if(this_num < photo_list.size()) {
			imgPath.append(photo_list.get(this_num).getPathName());
			photo = photo_list.get(this_num);
			next ++;
		}
		
		else {
			imgPath.append(photo_list.get(this_num - 1).getPathName());
			photo = photo_list.get(this_num - 1);
		}
		
		
		Date date = new Date(photo.getUploadTime());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String time = sdf.format(date);
		
		modelAndView.addObject("next", next);
		modelAndView.addObject("imgPath", imgPath.toString());
		modelAndView.addObject("totol", photo_list.size());
		modelAndView.addObject("description", photo.getDescription());
		modelAndView.addObject("time", time);
		
		modelAndView.setViewName("preOrnextFriendPhoto");
		
		return modelAndView;
	}
	
	
	/**
	 * 批量处理照片
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/batchPhoto.action")
	public ModelAndView batchPhoto(HttpServletRequest request, HttpSession session) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		
		
		String[] photos = request.getParameterValues("batchPhoto");
		
		String cmd = request.getParameter("submitform");
		
		if(photos != null && cmd.equals("删除")) {
			Map<Album, List<Photo>> userLoadingMap = (Map<Album, List<Photo>>) session.getAttribute("userLoadingMap");
			Album album = (Album) session.getAttribute("batchAlbum");
			List<Photo> photoList = userLoadingMap.get(album);
			for(int i=0; i<photos.length; i++) {
				//从数据库中删除照片
				photoService.deletePhotoByBatch(photos[i]);
				//删除session中的缓存
				for(Photo photo : photoList) {
					if(photo.getPathName().equals(photos[i])) {
						photoList.remove(photo);
						break;
					}
				}
				
			}
			modelAndView.setViewName("personal");
		}
		else if(photos != null && cmd.equals("下载")) {
			
			//打包要下载的图片
			
			Map<Album, List<Photo>> userLoadingMap = (Map<Album, List<Photo>>) session.getAttribute("userLoadingMap");
			Album album = (Album) session.getAttribute("batchAlbum");
			List<Photo> photoList = userLoadingMap.get(album);
			String username = (String) session.getAttribute("username");
			String basePath = request.getServletContext().getRealPath("/") + "imgdata/" + username + "file/" + album.getPathName() + "/";
			List<File> pic_files = new ArrayList<File>(); 
			for(int i=0; i<photos.length; i++) {
				for(Photo photo : photoList) {
					if(photo.getPathName().equals(photos[i])) {
						pic_files.add(new File(basePath + photos[i]));
						break;
					}
				}
				
			}
			
			File[] files = pic_files.toArray(new File[0]);
			
			String zipFilePath = request.getServletContext().getRealPath("/") + "imgdata/" + username + "file";
			
			//打包
			FilesToZip.fileToZip(files, zipFilePath, "download");
			
			modelAndView.addObject("zipPath","imgdata/" + username + "file/" + "download.zip");
			
			modelAndView.setViewName("personal");
			
		}
		
		
		return modelAndView;
	}
	
	
	/**
	 * 批量处理好友照片
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/batchFriendPhoto.action")
	public ModelAndView batchFriendPhoto(HttpServletRequest request, HttpSession session) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		
		
		String[] photos = request.getParameterValues("batchPhoto");
		
		String cmd = request.getParameter("submitform");
		
		
		if(photos != null && cmd.equals("下载")) {
			
			//打包要下载的图片
			
			Map<Album, List<Photo>> userLoadingMap = (Map<Album, List<Photo>>) session.getAttribute("friendLoadingMap");
			Album album = (Album) session.getAttribute("friend_batchAlbum");
			List<Photo> photoList = userLoadingMap.get(album);
			String username = (String) session.getAttribute("friendname");
			String basePath = request.getServletContext().getRealPath("/") + "imgdata/" + username + "file/" + album.getPathName() + "/";
			List<File> pic_files = new ArrayList<File>(); 
			for(int i=0; i<photos.length; i++) {
				for(Photo photo : photoList) {
					if(photo.getPathName().equals(photos[i])) {
						pic_files.add(new File(basePath + photos[i]));
						break;
					}
				}
				
			}
			
			File[] files = pic_files.toArray(new File[0]);
			
			String zipFilePath = request.getServletContext().getRealPath("/") + "imgdata/" + username + "file";
			
			//打包
			FilesToZip.fileToZip(files, zipFilePath, "download");
			
			modelAndView.addObject("zipPath","imgdata/" + username + "file/" + "download.zip");
			
			modelAndView.setViewName("displayFriendAlbums");
			
		}
		
		
		return modelAndView;
	}
	
	
	/**
	 * 下载全部照片
	 * @param request
	 * @param session
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	@RequestMapping("/downloadAll.action")
	public ModelAndView downloadAll(HttpServletRequest request, HttpSession session) throws IOException, InterruptedException {
		ModelAndView modelAndView = new ModelAndView();
		
		
		//压缩当前用户名下的所有照片
		String contextPath = request.getServletContext().getRealPath("/");
		String username = (String) session.getAttribute("username");
		
		String path = contextPath + "imgdata/" + username + "file";
		
		File[] files = (new File(path)).listFiles();
		
		File zipFile = new File(contextPath + "imgdata/" + username + "file/downloads.zip");
		
		System.out.println(zipFile.exists());
		
		System.out.println("删除：" + zipFile.delete());
		
		zipFile = new File(contextPath + "imgdata/" + username + "file/downloads.zip");
		System.out.println(zipFile.exists());
		
		//打包
		MultiZip.ZipFiles(zipFile, "downloads", files);
		
		System.out.println(zipFile.exists());
		modelAndView.addObject("zipPath","imgdata/" + username + "file/" + "downloads.zip");
		modelAndView.addObject("del", contextPath + "imgdata/" + username + "file/downloads.zip");
		modelAndView.setViewName("batchAction");
		
		
		return modelAndView;
	}
	
	
	/**
	 * 上传头像
	 * @param request
	 * @param session
	 * @param photoFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadHead.action")
	public ModelAndView uploadHead(HttpServletRequest request, HttpSession session, 
			MultipartFile photoFile) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		
		//将用户头像存在username文件夹下以username + head命名
		if(photoFile != null) {
			
			String username = (String) session.getAttribute("username");
			
			String original = photoFile.getOriginalFilename();
			
			String contextPath = request.getServletContext().getRealPath("/") + "imgdata/" + username + "file/";
			
			String headPath = contextPath + username + "head" + original.substring(original.lastIndexOf("."));
			
			File headFile = new File(headPath);
			if(headFile.exists()) {
				headFile.delete();
			}
			photoFile.transferTo(new File(headPath));
			
			//将头像所对应的照片名存入session。
			String head = username+"head"+original.substring(original.lastIndexOf("."));
			session.setAttribute("head", "imgdata/"+username+"file/"+head);
			
			//将头像所对应的照片名存入数据库
			UserInfo userInfo = new UserInfo();
			userInfo.setUsername(username);
			userInfo.setHead(head);
			userInfoService.uploadHead(userInfo);
			
			modelAndView.setViewName("personal");
		}
		
		
		
		return modelAndView;
	}
	
	
	
	
	

}
